--[[
 -- *名称:LobbyPart
 -- *描述:子游戏大厅
 -- *版权:Copyright © 2016-2018 深圳市三只小熊科技有限公司 版权所有
 -- *作者:Administrator
 -- *创建日期:2017-11-02
 -- *修改日期:2017-11-02
 ]]
local CURRENT_MODULE_NAME = ...
print("lobby module name = " .. CURRENT_MODULE_NAME)
local LobbyPart = class("LobbyPart", PokerPartBase) --大厅模块
LobbyPart.DEFAULT_PART = {--默认存在的固有组件
    "BroadcastPart", -- 跑马灯组件
    'DdzNoticePart', -- 公告组件
    'DdzHelpLayerPart', --帮助组件
    'RecordPart', --战绩组件
    'DdzSettingsPart', --设置组件
    'UserInfoPart', --个人信息组件
    'EnterRoomPart', --加入房间组件
    'CreateRoomPart', --创建房间组件
    "PurchasePart", --支付组件
    "MessageDialogPart", 
}
LobbyPart.DEFAULT_VIEW = "lobbyscene"
require("app.model.config.RoomConfig")
require("app.model.protobufmsg.game_message_pb")
require("app.model.protobufmsg.wllobby_message_pb")
require("app.model.config.ClientParamConfig")
--[
-- @brief 构造函数
--]
function LobbyPart:ctor(owner)
    LobbyPart.super.ctor(self, owner)
    self:initialize();
end

function LobbyPart:dtor(...)
    Log.d("LobbyPart:dtor");
    LobbyPart.super.dtor(self, ...);
end
--[
-- @override
--]
function LobbyPart:initialize()
    cc.bind(self, "purchaselogic");
    cc.bind(self, "sharelogic");
    cc.bind(self, "agentlogic");
    cc.bind(self, "roomlogic");
end
---
-- 账号在其他地方登陆
-- @DateTime 2017-11-01
-- @param    data [description]
-- @param    appId [description]
-- @return    [description]
--
function LobbyPart:_otherLogin(data, appId)
    global:getNetManager():disconnect()
    self:_showTips(string_table.other_login, 1, false, function ()
        cc.Director:getInstance():endToLua()
    end);
end
---
-- 物理返回键按钮
-- @DateTime 2017-11-06
-- @param     [description]
-- @return    [description]
--
function LobbyPart:backEvent(...)
    print("LobbyPart.backEvent ...")
    self:release()
    local basepartconfig = "app.BasePartConfig"
    package.loaded[basepartconfig] = nil --清空配置信息
    require(basepartconfig)
    local hj_lobby_part = global:createPart(PartConfig.MainLobby, global:getGameUser())
    if hj_lobby_part then
        hj_lobby_part:activate(LOBBY_GAME_ID)
    end
end
---
-- 激活大厅模块
-- @DateTime 2017-11-06
-- @param    gameId [description]
-- @return    [description]
--
function LobbyPart:activate(gameId)
    LobbyPart.super.activate(self, CURRENT_MODULE_NAME)
    Log.d("LobbyPart:activate");
    local lua_bridge = global:getModuleWithId(ModuleDef.BRIDGE_MOD);
    
    if IOS_BACK_DELAY == true then
        IOS_BACK_DELAY = false
        if lua_bridge.setBackDelayTime then
            lua_bridge:setBackDelayTime(30000)
        end
    end
    
    DdzGameConfig.GAME_ID = gameId
    self.reconnect_flag = nil 
    
    lua_bridge:changeActivityOrientation(1); -- 设置横屏
    global:getNetManager():enableSeq(false) --是否开启双序号 true 开启 false 关闭 
    
    local props = global:getGameUser():getProps()
    self:doView("updateUserInfo", props);
    self._playerID = props["gameplayer" .. DdzGameConfig.GAME_ID].playerIndex
    self._name = props.name
    
    self:initBroadcastNode();
    
	SoundMgr.playMusic(SoundMgr.SoundId.BGM);
end
---
-- 反激活组件
-- @DateTime 2017-11-03
-- @return   [description]
--
function LobbyPart:deactivate()
    Log.d("LobbyPart:deactivate");
    --移除内存检测
    if self._keyListener and self.view then
        self.view:getEventDispatcher():removeEventListener(self._touchListener)
        self._touchListener = nil ;
    end
    LobbyPart.super.deactivate(self);
    CleanUtils.clean(GamePath);
    Log.d("检测内存泄漏：");

	SoundMgr.stopMusic();
	SoundMgr.playDefaultBGM();
end
---
-- 初始化跑马灯节点
-- @DateTime 2017-11-06
-- @return   [description]
--
function LobbyPart:initBroadcastNode()
    local broadcastPart = self:getPart("BroadcastPart")
    if broadcastPart then
        broadcastPart:activate();
        if broadcastPart.view then 
            broadcastPart.view:setPosition(640, 600);
        end
    end
end
---
-- 登录子游戏大厅成功
-- @DateTime 2017-11-06
-- @param    data [description]
-- @return    [description]
--
function LobbyPart:_onLobbyLoginAck(data)
	-- 重连登录成功
	local fnSuccess = function( loginAckData ) 
        self:requestLoginGame(DdzGameConfig.GAME_ID);
    end

    -- 重连登录不成功切换到登录界面
    local fnFailed = function ( loginAckData )
        self:_returnLogin()
    end

    self:handleReconnectAck(data, fnSuccess, fnFailed);
end
---
-- 登录子游戏成功
-- @DateTime 2017-11-06
-- @param    data [description]
-- @return    [description]
--
function LobbyPart:_onGameLoginAck(data)
   	self:stopLoading();
    local fn = function( loginAckData ) 
    	self:activate(DdzGameConfig.GAME_ID)
	end

    self:handleGameLoginAck(data, fn);
end
--[[
 -- 收到玩家钻石更新
 -- @DateTime 2017-11-27
 -- @param    data [description]
 -- @param    appId [description]
 -- @return    [description]
 ]]
function LobbyPart:_onUpdatePlayerProperty(data, appId)
	local fnCallback = function (  )
	    if self.view then
	        self:doView("updateUserInfo", user:getProps());
	    end
	end

	self:updatePlayerProperty(DdzGameConfig.GAME_ID, data, fnCallback);
end
---
-- 斗地主桌面信息初始化
-- @DateTime 2017-11-06
-- @param    data [description]
-- @return    [description]
--
function LobbyPart:initTableInfo(data)
    print("DDZLobbyPart init table info", data)
    local table_part = self:getPart("TablePart")
    if table_part then
        self:deactivate()
        table_part:activate(data)
    end
end
---
-- 获取PartId
-- @DateTime 2017-11-06
-- @return   [description]
--
function LobbyPart:getPartId()
    return "LobbyPart"
end
---
-- 激活公告组件
-- @DateTime 2017-10-30
-- @return   [description]
--
function LobbyPart:noticeClick()
    self:activatePart("DdzNoticePart");
end
---
-- 请求商城数据 
-- @DateTime 2017-11-06
-- @return   [description]
--
function LobbyPart:reqShopData()
    self:_getAgenConfig(3);
end
---
-- 点击玩法按钮
-- @DateTime 2017-11-01
-- @return   [description]
--
function LobbyPart:helpClick()
    local part = self:activatePart("DdzHelpLayerPart")
    if part then
        part:showView();
    end
end
---
-- 打开战绩
-- @DateTime 2017-11-02
-- @return   [description]
--
function LobbyPart:recordClick()
    self:activatePart("RecordPart", self._playerID, self._name);
end
---
-- 设置按钮点击事件
-- @DateTime 2017-11-02
-- @return   [description]
--
function LobbyPart:settingsClick()
    self:activatePart("DdzSettingsPart");
end
---
-- 分享点击事件
-- @DateTime 2017-11-02
-- @return   [description]
--
function LobbyPart:reqShare()
    Log.d("LobbyPart:reqShare");
    self:shareToFriend("未来斗地主", nil, nil);
end

function LobbyPart:headClick()
    local user = global:getGameUser()
    local recommender_Id = user:getProp("recommender_Id" .. DdzGameConfig.GAME_ID)
    local recommenderId = recommender_Id.recommenderId
    local type = ""
    if recommenderId == 0 then
        type = nil
    else
        type = "apply_agency"
    end
    local user_info_part = self:getPart("UserInfoPart")
    if user_info_part then
        user_info_part:activate(DdzGameConfig.GAME_ID, type)
    end
end

function LobbyPart:addDiamonds()
    Log.d("LobbyPart:addDiamonds");
    self:reqShopData()
end

---
 -- 合集大厅调用，不可删
 -- 每次登录成功后需要调用一次重连判断是不是有断线重连
 -- @DateTime 2017-11-21
 -- @param    reconnectFlag [description]
 -- @param    gameId [description]
 -- @return    [description]
 --
function LobbyPart:reconnectRequest(reconnectFlag, gameId)
    DdzGameConfig.GAME_ID = gameId
    self.reconnect_flag = reconnectFlag
    
    local lua_bridge = global:getModuleWithId(ModuleDef.BRIDGE_MOD)
    if IOS_BACK_DELAY == false then
        IOS_BACK_DELAY = true
        
        lua_bridge:setBackDelayTime(30000)
    end
    lua_bridge:changeActivityOrientation(1) 
    
    global:getNetManager():enableSeq(false) --是否开启双序号 true 开启 false 关闭  
    self:startLoading()
    
    self:requestStartGame(DdzGameConfig.GAME_ID);
end

function LobbyPart:requestStartGameClick()
    self:startLoading();
    self._curOperateType = 2
    self:requestStartGame(DdzGameConfig.GAME_ID);
end

function LobbyPart:createVipGameClick()
    self:startLoading()
    self._curOperateType = 1
    self:requestStartGame(DdzGameConfig.GAME_ID);
end

function LobbyPart:_onEnterRoomAck(data, appID)
    -- 这里要根据游戏类型跳转到不同的游戏进行处理
    self:stopLoading();
    local enter_room_ack = ddzCommon_pb.StartGameMsgAck()
    enter_room_ack:ParseFromString(data)
    local result = enter_room_ack.result;
    local msgResult = SocketConfig.MsgResult;
    Log.d("LobbyPart:_onEnterRoomAck result: ", result);
    if result == msgResult.GOLD_LOW_THAN_MIN_LIMIT then -- 金币低于下限
        self:_showTips(string_table.gold_low, 1, true);
    elseif result == msgResult.GOLD_HIGH_THAN_MAX_LIMIT then -- 金币超过上限
    elseif result == msgResult.CAN_ENTER_VIP_ROOM then -- 可以进入VIP房间
        if self.reconnect_flag then --异常容错，正常情况，有重连标记就应该重连进入房间，如果服务端数据错误，保证还很显示大厅
            global:exitLobby()
            self:activate(DdzGameConfig.GAME_ID)
        elseif self._curOperateType == 1 then
            self:createRoom()
        elseif self._curOperateType == 2 then
            self:addRoom()
        end
    elseif result == msgResult.VIP_TABLE_IS_FULL then -- vip桌 子已经满座了
        self:_showTips(string_table.vip_table_is_full, 1, true);
    elseif result == msgResult.VIP_TABLE_IS_GAME_OVER then -- 正在游戏中不能进入其他房间
        self:_showTips(string_table.vip_table_is_over, 1, true);
    elseif result == msgResult.IS_PLAYING_CAN_NOT_ENTER_ROOM then -- 正在游戏中不能进入其他房间
        self:_showTips(string_table.is_playing_cannot_enter, 1, true);
    elseif result == msgResult.TODAY_GAME_RECORD_OUT_LIMIT_IN_ROOM then -- 今日输赢超过房间上限
        self:_showTips(string_table.room_record_out_limit, 1, true);
    elseif result == msgResult.TODAY_GAME_RECORD_OUT_LIMIT_IN_GAME then -- 今日输赢超过游戏上限
        self:_showTips(string_table.game_record_out_limit, 1, true);
    elseif result == msgResult.VIP_TABLE_NOT_FOUND then -- 桌子未找到
        local add_room_part = self:getPart("EnterRoomPart")
        if add_room_part then
            add_room_part:deactivate()
        end
        self:_showTips(string_table.room_id_wrong, 1, true);
    elseif result == msgResult.FANGKIA_NOT_FOUND then --钻石不足
        self:_showTips(string_table.fangka_not_found, 1, true);
    elseif result == msgResult.CMD_EXE_OK then --进入房间
        self:_enterRoom(enter_room_ack)
    elseif result == msgResult.CAN_NOT_FOUND_ROOM then 
        self:_showTips(DdzString.can_not_found_room, 1, true);
    elseif result == msgResult.CAN_NOT_FOUND_TABLE then 
        self:_showTips(DdzString.can_not_found_table, 1, true);
    elseif result == msgResult.CAN_NOT_FOUND_PLAYER then 
        self:_showTips(DdzString.can_not_found_player, 1, true);
    elseif result == msgResult.PLAYER_ALREADY_IN_TABLE then 
        self:_showTips(DdzString.player_already_in_table, 1, true);
    elseif result == msgResult.CAN_NOT_ENTER_TABLE then 
        self:_showTips(DdzString.can_not_enter_table, 1, true);
    elseif result == msgResult.CAN_NOT_BE_PREPARED then 
        self:_showTips(DdzString.can_not_be_prepared, 1, true);
    elseif result == msgResult.CAN_NOT_EXPOSE_CARD then 
        self:_showTips(DdzString.can_not_expose_card, 1, true);
    elseif result == msgResult.CAN_NOT_CALL_SCORE then 
        self:_showTips(DdzString.can_not_call_score, 1, true);
    elseif result == msgResult.CAN_NOT_DISCARD then 
        self:_showTips(DdzString.can_not_discard, 1, true);
    elseif result == msgResult.CAN_NOT_VOTE_CLOSE_ROOM then 
        self:_showTips(DdzString.can_not_vote_close_room, 1, true);
    elseif result == DdzGameConfig.MsgResult.CAN_NOT_FOUND_ROOM then 
        self:_showTips(DdzString.can_not_found_room, 1, true);
    elseif result == DdzGameConfig.MsgResult.CAN_NOT_FOUND_TABLE then
        self:_showTips(DdzString.can_not_found_table, 1, true);
    end
end
---
-- 进入房间
-- @DateTime 2017-11-02
-- @param    data [description]
-- @return    [description]
--
function LobbyPart:_enterRoom(data)
    Log.d("LobbyPart:_enterRoom");
    
    local user = global:getGameUser()

    local tablePart = user:getPart("TablePart");
    tablePart = tablePart or global:createPart("TablePart", user);
    if tablePart then
        print("activate tableinfo ")
        self:release()
        tablePart:activate(data)
    end
    --[[local lua_bridge = global:getModuleWithId(ModuleDef.BRIDGE_MOD)
    if lua_bridge:getMWLobbyStatus() then
        lua_bridge:setMWStatus(false)
end]]
end

function LobbyPart:_onScrollMsgAck(data, appId)--跑马灯消息
    local net_manager = global:getNetManager()
    local scroll_msg = wllobby_message_pb.ScrollMsg()
    scroll_msg:ParseFromString(data)
    --print("----_onScrollMsgAck : ",scroll_msg)
    local msg = scroll_msg.msg
    local loopNum = scroll_msg.loopNum
    local removeAll = scroll_msg.removeAll
    
    self:callPartMethod("BroadcastPart", "startBroadcast", msg, loopNum, removeAll, false)
end

function LobbyPart:_notifyMsgAck(data, appId)--系统消息
    local net_manager = global:getNetManager()
    local notify_Msg = wllobby_message_pb.SystemNotifyMsg()
    notify_Msg:ParseFromString(data)
    --print("----_onScrollMsgAck : ",notify_Msg) 系统消息暂时屏蔽  太刷屏了
end
---
-- 请求代理、商城配置
-- @DateTime 2017-10-31
-- @param    flag [description]
-- @return    [description]
--
function LobbyPart:_getAgenConfig(flag)
    self:startLoading()
    self.agentFlag = flag
    local reqAgencyData = hjlobby_message_pb.GetGameConfigReq()
    reqAgencyData.type = 4
    global:getNetManager():sendProtoMsg(reqAgencyData, DdzSocketConfig.REQ_GAME_CONFIG, SocketConfig.GAME_ID)
end
---
-- 返回登陆界面
-- @DateTime 2017-10-31
-- @return   [description]
--
function LobbyPart:_returnLogin()
    local user = global:getGameUser();
    self:deactivate();
    local login_part = global:createPart("LoginPart", user);
    user:addPart(login_part);
    login_part:activate(LOBBY_GAME_ID);
    login_part:showLogin();
end
---
-- 弹出提示框
-- @DateTime 2017-10-31
-- @param    content [description]
-- @param    type [description]
-- @param    canClose [description]
-- @param    confirmFunc [description]
-- @param    cancelFunc [description]
-- @return    [description]
--
function LobbyPart:_showTips(content, type, canClose, confirmFunc, cancelFunc)
    Log.d("LobbyPart:_showTips content: ", content);
    local data = {};
    data.type = 1;
    data.canClose = false;
    data.callback = {
        confirmFunc = confirmFunc, 
        cancelFunc = cancelFunc
    };
    data.content = content;
    self:_showMessageDialog(data);
end
---
-- 收到游戏配置消息GameConfig
-- @DateTime 2017-10-30
-- @param    data [description]
-- @return    [description]
--
function LobbyPart:_onResGameConfig(data)
	self:stopLoading();
    local gameConfigData = hjlobby_message_pb.GetGameConfigRsp();
    gameConfigData:ParseFromString(data);
    print("LobbyPart:_onResGameConfig", gameConfigData);
    
    if self.agentFlag == 1 or self.agentFlag == 2 then 
        self:handleAgent(SocketConfig.GAME_ID, self.agentFlag, gameConfigData);
    elseif self.agentFlag == 3 then 
        --点击商城
        self:requestPurchaseConfig(DdzGameConfig.GAME_ID, handler(self, self._onRequestPurchaseConfigCallback));
    end
    self.agentFlag = nil;
    
    self:dispatchEvent(DdzEventConfig.EVENT_GET_GAME_CONFIG, gameConfigData);
end
---
-- 发送Http请求接收商品配置回调方法
-- @DateTime 2017-11-02
-- @param    resultCode [description]
-- @param    data [description]
-- @return    [description]
--
function LobbyPart:_onRequestPurchaseConfigCallback(resultCode, data)
    Log.d("LobbyPart:_onRequestPurchaseConfigCallback resultCode: ", resultCode);
    Log.d("LobbyPart:_onRequestPurchaseConfigCallback data: ", data);
    if resultCode == HTTP_STATE_SUCCESS then
        local table_data = cjson.decode(data)
        if ISAPPSTORE then
            self:activatePart("PurchasePart", self.m_gameID, table_data.list);
        else
            Log.d("LobbyPart:_onRequestPurchaseConfigCallback referrer_id: ", table_data.referrer_id);
            -- table_data.referrer_id = 999;
            if table_data.referrer_id ~= 0 then--已绑定代理人
                self:activatePart("PurchasePart", self.m_gameID, table_data.list);
            else
                self:_getAgenConfig(2); --跳转web绑定代理人
            end
        end
    end
    self:stopLoading();
end
---
-- 弹出提示框
-- @DateTime 2017-10-30
-- @param    data = {
--  type = 1 or 2, 
--  content = "", 
--  canClose = true or false, 
--  callback = {
--  confirmFunc = function, 
--  cancelFunc = function
--  } 
--  }
-- @return   nil
--
function LobbyPart:_showMessageDialog(data)
    self:activatePart("MessageDialogPart", data);
end
---
-- 点击代理按钮
-- @DateTime 2017-11-01
-- @return   [description]
--
function LobbyPart:agentClick()
    self:_getAgenConfig(1)
end
---
-- 创建房间
-- @DateTime 2017-10-31
-- @return   [description]
--
function LobbyPart:createRoom()
    self:activatePart("CreateRoomPart");
end
---
-- 加入房间
-- @DateTime 2017-10-31
--
function LobbyPart:addRoom()
    self:activatePart("EnterRoomPart");
end
---
-- 返回合集大厅
-- @DateTime 2017-10-31
-- @return   [description]
--
function LobbyPart:returnLobby()
    self:release()
    local hj_lobby_part = global:createPart("HjLobbyPart", global:getGameUser())
    if hj_lobby_part then
        hj_lobby_part:activate(LOBBY_GAME_ID)
    end
    --collectgarbage("collect")
    if g_GameMonitor then
        xxtimer.delay(0.3, function()
            g_GameMonitor:update(100);
            g_GameMonitor:showReferences();
        end); 
    end
end
---
-- 返回战绩
-- @DateTime 2017-11-09
-- @param    data [description]
-- @return    [description]
--
function LobbyPart:_onResGameHistory(data)
    local gameHistory = ddz_pb.RoomScoreRecordListACK();
    gameHistory:ParseFromString(data);
    EventMgr.dispatchEvent(DdzEventConfig.REC_GAME_HISTORY, gameHistory);
end
---
-- 网络事件监听配置
-- @type {Object}
--
LobbyPart.eventFuncMap = {
    [DdzSocketConfig.RES_GAME_CONFIG] 				= LobbyPart._onResGameConfig;
    [DdzSocketConfig.RES_GAME_HISTORY] 				= LobbyPart._onResGameHistory;
    [SocketConfig.MSG_GAME_OTHERLOGIN_ACK] 			= LobbyPart._otherLogin;
    [SocketConfig.MSG_REQUEST_START_GAME_ACK] 		= LobbyPart._onEnterRoomAck;
    [SocketConfig.MSG_GAME_SEND_SCROLL_MES] 		= LobbyPart._onScrollMsgAck;
    [SocketConfig.MSG_SYSTEM_NOTIFY_MSG] 			= LobbyPart._notifyMsgAck;
    [SocketConfig.MSG_GAME_UPDATE_PLAYER_PROPERTY] 	= LobbyPart._onUpdatePlayerProperty;
    [SocketConfig.MSG_GAME_LOGIN_ACK] 				= LobbyPart._onGameLoginAck;
    [CommonSocketConfig.ACK_LOGIN] 					= LobbyPart._onLobbyLoginAck;
};

return LobbyPart;

